package com.dawnling.androidutils.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyPaintView extends View {
    private List<Point> allPoints = new ArrayList<Point>();

    //接受context以及属性集合(宽度，高度等)
    public MyPaintView(Context context, AttributeSet attrs) {
        super(context, attrs);
        super.setOnTouchListener(new OnTouchListenerImp());
    }

    private class OnTouchListenerImp implements OnTouchListener {
        public boolean onTouch(View v, MotionEvent event) {
            Point p = new Point((int) event.getX(), (int) event.getY());
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //用户按下，表示重新开始保存点
                MyPaintView.this.allPoints = new ArrayList<>();
                MyPaintView.this.allPoints.add(p);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                //用户松开
                MyPaintView.this.allPoints.add(p);
                MyPaintView.this.postInvalidate();//重绘图像
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                MyPaintView.this.allPoints.add(p);
                MyPaintView.this.postInvalidate();//重绘图像
            }
            return true;
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void draw(Canvas canvas) {
        Paint p = new Paint();//依靠此类开始画线
        p.setColor(Color.RED);
        if (MyPaintView.this.allPoints.size() > 1) {
            //如果有坐标点，开始绘图
            Iterator<Point> iter = MyPaintView.this.allPoints.iterator();
            Point first = null;
            Point last = null;
            while (iter.hasNext()) {
                if (first == null) {
                    first = iter.next();
                } else {
                    if (last != null) {
                        first = last;
                    }
                    last = iter.next();//结束
                    canvas.drawLine(first.x, first.y, last.x, last.y, p);
                }
            }
        }
    }
}
